<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/11
 * Time: 17:28
 */
namespace app\admin\collection;
use think\Db;
use app\admin\collection\permissionCollection;

class  menuCollection{
    /**
     * 【超级管理员获取所有菜单】
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function getAllMenu(){
        $where = array('pid'=>0, 'type'=>0, 'status'=>0,'if_menu' => 1);
        $main_menu = Db::name("permission")
            ->where($where)
            ->field('id,icon,name,path')
            ->order('id asc')
            ->select();
        //获取各主菜单的子菜单
        if(count($main_menu) > 0){
            foreach($main_menu as $key=>&$v){
                //查询是否有子菜单
                $has_child = Db::name("permission")
                    ->where($where)
                    ->where('pid', $v['id'])
                    ->field('id,name,path')
                    ->order('id asc')
                    ->select();
                if(count($has_child) > 0){
                    $v['child'] = $has_child;
                }
            }
        }
        return $main_menu;
    }

    /**
     * 【根据用户ID获取菜单】
     * @param $user_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function getMenu($user_id){
        //获取该用户所在部门及角色
        $user_role = permissionCollection::getUserGroupRoleByUserId($user_id);

        //根据部门及角色查询所拥有的权限
        $role_permission = permissionCollection::getUserPermissionByGroupRole($user_role['group_id'], $user_role['role_id']);
        //dump($role_permission);exit;
        $nodes_str = $role_permission['permission_id'];
        if(count($role_permission) > 0){
            //获取当前用户的菜单权限(主菜单)
            $where = array('pid'=>0, 'status'=>0,'if_menu' => 1);
            $main_menu = Db::name("permission")
                ->where($where)
                ->where('id', 'in' , $nodes_str)
                ->field('id,icon,name,path')
                ->order('id asc')
                ->select();
            //获取各主菜单的子菜单
            if(count($main_menu) > 0){
                foreach($main_menu as $key=>&$v){
                    //查询是否有子菜单
                    $has_child = Db::name("permission")
                        ->where($where)
                        ->where('pid', $v['id'])
                        ->where('id', 'in' , $nodes_str)
                        ->field('id,name,path')
                        ->order('id asc')
                        ->select();
                    if(count($has_child) > 0){
                        $v['child'] = $has_child;
                    }
                }
            }
            return $main_menu;
        }

    }
}